package cn.itcast.bos.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.core.MediaType;

import org.apache.commons.io.FileUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.constant.Constants;
import cn.itcast.bos.domain.page.PageBean;
import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.utils.BaseAction;
import freemarker.template.Configuration;
import freemarker.template.Template;

@Controller
@Scope("prototype")
@ParentPackage("json-default")
@Namespace("/")
public class PromotionAction extends BaseAction<Promotion> {
	@SuppressWarnings("unchecked")
	@Action(value = "promotion_pagequery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {
		PageBean<Promotion> collection = WebClient
				.create("http://localhost:9001/bos_management/services/promotionService/pageQuery?page=" + page
						+ "&rows=" + rows)
				.accept(MediaType.APPLICATION_JSON).get(PageBean.class);
		ActionContext.getContext().getValueStack().push(collection);
		return SUCCESS;
	}

	@Action(value = "promotio_showDetail")
	public String showDetail() throws Exception {
		String realPath = ServletActionContext.getServletContext().getRealPath("/freemarker");
		File file = new File(realPath + "/" + model.getId() + ".html");
		// 如果文件不存在,查询数据库结合模板对象生成html
		if (!file.exists()) {
			Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
			configuration.setDirectoryForTemplateLoading(new File("/WEB-INF/template_freemarker"));
			// 获取模板
			Template template = configuration.getTemplate("promotion_detail.ftl");
			// 查询数据库获取动态数据
			Promotion promotion = WebClient.create(Constants.BOS_MANAGEMENT_HOST
					+ "/bos_management/services/promotionService/findPromotion/" + model.getId())
					.accept(MediaType.APPLICATION_JSON).get(Promotion.class);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("promotion", promotion);
			// 合并输出
			template.process(map, new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
		}
		// 如果文件存在,直接返回
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		FileUtils.copyFile(file, ServletActionContext.getResponse().getOutputStream());
		return NONE;
	}

	
}
